package com.laicunba.ext.activity.act20170807;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.constant.FinancingTargetConstant;
import com.laicunba.event.ActivityJoinEvent;
import com.laicunba.pojo.ActivityDO;
import com.laicunba.pojo.ActivityJoinDO;
import com.laicunba.pojo.CashCouponDefDO;
import com.laicunba.pojo.FinancingTargetDO;
import com.laicunba.pojo.RateIncrCouponDefDO;
import com.laicunba.pojo.VcoinWalletDO;
import com.laicunba.service.ActivityJoinService;
import com.laicunba.service.ActivityService;
import com.laicunba.service.CashCouponDefService;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.RateIncrCouponDefService;
import com.laicunba.service.VcoinWalletService;
import com.laicunba.service.accounting.RewardBidService;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;

/**
 * 2周年庆参与活动监听
 * 
 * @author lws
 *
 */
@Component
public class AnniversaryActivityListener implements ApplicationListener<ActivityJoinEvent> {
	private static final String gather_activityId = "20170807";
	
    private static final String box_activityId = "20170814box";
	
	private static final String lottery_activityId = "20170814lottery";
	
	@Autowired
	private VcoinWalletService vcoinWalletService;
	@Autowired
	private CashCouponDefService cashCouponDefService;
	@Autowired
	private RateIncrCouponDefService rateIncrCouponDefService;
	@Autowired
	private ActivityJoinService activityJoinService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private FinancingTargetService financingTargetService;
	@Autowired
	private RewardBidService rewardBidService;
	
	@Override
	public void onApplicationEvent(ActivityJoinEvent event) {
		ActivityJoinDO joinDO = (ActivityJoinDO) event.getSource();
		if (!gather_activityId.equalsIgnoreCase(joinDO.getActivityId()) 
		    && !box_activityId.equalsIgnoreCase(joinDO.getActivityId())
		    && !lottery_activityId.equalsIgnoreCase(joinDO.getActivityId())) {
			return;
		}
		
		ActivityDO activity = activityService.get(ActivityDO.class, joinDO.getActivityId());
		if(activity == null || activity.getBeginTime().after(new Date()) || activity.getEndTime().before(new Date())) {
			return;
		}
		if (joinDO != null && StringUtil.isNotEmpty(joinDO.getUserId(), joinDO.getSubActId())) {
			// 集结号
			if (gather_activityId.equalsIgnoreCase(joinDO.getActivityId())){
				// 当前邀请豆
				String currentInviteSoy = CacheUtil.getAttribute("act.anniversary.2017invitesoy." + joinDO.getUserId());
				if(StringUtil.isEmpty(currentInviteSoy)) {
					currentInviteSoy = "0";
				}
				
				int needExchangeSoy = getNeedExchangeSoy(Integer.parseInt(joinDO.getSubActId()));
				String rateIncrId = getRateIncrByType(Integer.parseInt(joinDO.getSubActId()));
				
//				AssertUtil.assertTrue(currentInviteSoy >= needExchangeSoy, "INNIVERSARY_ACTIVITY_INVITESOY_NOT_ENOUGH");
				if (Integer.parseInt(currentInviteSoy) < needExchangeSoy) {
					joinDO.setRewardResp("邀请豆不足，快快召唤好友");
					joinDO.setStatus("fail");
				} else {
					anniversaryActivityExchangeCoupon(joinDO.getUserId(), Integer.parseInt(currentInviteSoy), needExchangeSoy, rateIncrId);
					// 减少邀请豆
					CacheUtil.setAttribute("act.anniversary.2017invitesoy." + joinDO.getUserId(), 
							String.valueOf(Integer.parseInt(currentInviteSoy) - needExchangeSoy), 25 * 24 * 60 * 60);
					
					joinDO.setRewardResp("红包已兑换请至“我的红包”查看");
					joinDO.setStatus("success");
				}
				
			} else if (box_activityId.equalsIgnoreCase(joinDO.getActivityId())){ // 宝箱大探险
				String currentOpenBoxChange = CacheUtil.getAttribute("act.anniversary.2017openboxchange." + joinDO.getUserId());
				if (StringUtil.isEmpty(currentOpenBoxChange)) {
					currentOpenBoxChange = "0";
				}
				
				int openBoxType = Integer.parseInt(joinDO.getSubActId());
				String couponId = "";
				String rewardType = "";
				boolean isUseIntegral = true;
				if (openBoxType == 1) {// 青铜
					if (Integer.parseInt(currentOpenBoxChange) > 0) {
						Map<String, String> lotteryMap = openBox(openBoxType, true, joinDO.getUserId(), 0, getBoxCouponArray(openBoxType));
						if (lotteryMap!=null && lotteryMap.size() > 0 && StringUtil.isNotEmpty(lotteryMap.get("rewardType"))) {
							couponId = lotteryMap.get("rewardCoupon");
							rewardType = lotteryMap.get("rewardType");
							
							// 减少开启宝箱的机会
							int days = DateUtil.days(activity.getBeginTime(), activity.getEndTime());
							CacheUtil.setAttribute("act.anniversary.2017openboxchange." + joinDO.getUserId(), 
									String.valueOf(Integer.parseInt(currentOpenBoxChange) - 1), days * 24 * 60 * 60);
						}
						
						isUseIntegral = false;
					} 
				} 
				int needBoxIntegral = getNeedBoxIntegral(openBoxType);
				if(isUseIntegral) {
//					AssertUtil.assertTrue(needBoxIntegral > 0, "INNIVERSARY_ACTIVITY_INVITESOY_NOT_ENOUGH");
					
					VcoinWalletDO vcoinWalletDO = vcoinWalletService.get(VcoinWalletDO.class, joinDO.getUserId());
					if (vcoinWalletDO == null) {
						vcoinWalletDO = vcoinWalletService.get(VcoinWalletDO.class, joinDO.getUserId());
					}
					AssertUtil.assertNotNull(vcoinWalletDO, "VCOINWALLET_IS_NULL");
//					AssertUtil.assertTrue(vcoinWalletDO.getBalance() >= needBoxIntegral, "INNIVERSARY_ACTIVITY_INVITESOY_NOT_ENOUGH");
					if (vcoinWalletDO.getBalance() < needBoxIntegral) {
						if (openBoxType == 1) {
							joinDO.setRewardResp("当前积分不足，投资或邀请好友赢取机会！");
							joinDO.setStatus("fail");
						} else {
							joinDO.setRewardResp("当前积分不足，投资赚取积分！");
							joinDO.setStatus("fail");
						}
					} else {
						Map<String, String> lotteryMap = openBox(openBoxType, true, joinDO.getUserId(), 0, getBoxCouponArray(openBoxType));
						if (lotteryMap!=null && lotteryMap.size() > 0 && StringUtil.isNotEmpty(lotteryMap.get("rewardType"))) {
							couponId = lotteryMap.get("rewardCoupon");
							rewardType = lotteryMap.get("rewardType");
						}
					}
					
					// 积分减少
					vcoinWalletService.subtract(joinDO.getUserId(), needBoxIntegral, "CELEBRATE_DEPOSITORY_ONLINE", "2周年庆活动参与开启大宝箱");
				}
				// 现金券赠送
				if (StringUtil.isNotEmpty(couponId)) {
					String couponDesc = "";
					joinDO.setRewardType(rewardType);
					if (couponId.startsWith("material")) {
						String couponValue = couponId.substring(couponId.lastIndexOf("-") + 1);
						if (couponId.startsWith("material-jingdong-ecard")) {
							joinDO.setRewardResp("恭喜您，获得" + couponValue + "元京东E卡，将以短信形式发送！");
							couponDesc = couponValue + "元京东E卡";
						} else {
							joinDO.setRewardResp("恭喜您，获得" + couponValue + "，活动结束后由客服联系并为您寄出！");
							couponDesc = couponValue;
						}
					} else {
						if (couponId.equals("act-two-anniversary-celebrate-bronze-coupon-0.37")) {
							RateIncrCouponDefDO rateIncrCouponDefDO = rateIncrCouponDefService.get(RateIncrCouponDefDO.class, couponId);
							if (rateIncrCouponDefDO != null) {
								rateIncrCouponDefService.send2User(couponId, joinDO.getUserId(), false, "2周年宝箱大探险活动开启宝箱赠送加息券");
								joinDO.setRewardResp("恭喜您，获得"+ rateIncrCouponDefDO.getRate().doubleValue() +"%加息券");
								couponDesc = rateIncrCouponDefDO.getRate().doubleValue() +"%加息券";
							}
						} else {
							CashCouponDefDO couponDef = cashCouponDefService.get(CashCouponDefDO.class, couponId);
							if (couponDef != null) {
								cashCouponDefService.send2UserWithMessage(couponDef.getId(), joinDO.getUserId(), false,"2周年宝箱大探险活动开启宝箱赠送现金券");
								joinDO.setRewardResp("恭喜您，获得"+ couponDef.getAmount() +"元现金券");
								couponDesc = couponDef.getAmount() +"元现金券";
							}
						}
					}
					String summary = "";
					if(isUseIntegral) {
						summary = "{\"consume\":\""+ needBoxIntegral +"积分\",\"couponDesc\":\"" + couponDesc + "\"}";
					} else {
						summary = "{\"consume\":\"一次开启机会\",\"couponDesc\":\"" + couponDesc + "\"}";
					}
					joinDO.setSummary(summary);
					joinDO.setStatus("success");
				}
				
			} else if (lottery_activityId.equalsIgnoreCase(joinDO.getActivityId())){ // 大转盘抽奖
				String currentLotteryDrawChance = CacheUtil.getAttribute("act.anniversary.2017lotterydrawchance." + joinDO.getUserId());
				String isUseSendChangeFlag = CacheUtil.getAttribute("act.anniversary.2017lotterydrawchance.usesendchangeflag." + joinDO.getUserId() + DateUtil.formatDate(new Date()));
				if (StringUtil.isEmpty(currentLotteryDrawChance) || Integer.parseInt(currentLotteryDrawChance) == 0) {
					joinDO.setRewardResp("抽奖次数已用完，邀请好友赢取机会！");
					joinDO.setStatus("fail");
				} else {
					boolean isUseSendChange = false; // 是否使用赠送的机会
					if (isUseSendChangeFlag == null || Integer.parseInt(isUseSendChangeFlag) == 0) {
						isUseSendChange = true;
					}
					Map<String, String> lotteryMap = lottery();
					if (lotteryMap!=null && lotteryMap.size() > 0 && StringUtil.isNotEmpty(lotteryMap.get("rewardType"))) {
						String couponId = lotteryMap.get("rewardCoupon");
						String rewardType = lotteryMap.get("rewardType");
						
						if ("3".equals(rewardType) || "5".equals(rewardType) || "6".equals(rewardType)) {
							RateIncrCouponDefDO rateIncrCouponDefDO = rateIncrCouponDefService.get(RateIncrCouponDefDO.class, couponId);
							if (rateIncrCouponDefDO != null) {
								String rewardResp = "恭喜您，获得" + rateIncrCouponDefDO.getRate().doubleValue() + "%的加息券！";
								if (!isUseSendChange) {
									rateIncrCouponDefService.send2User(couponId, joinDO.getUserId(), false, "2周年大转盘抽奖赠送加息券");
									rewardResp = "恭喜您，获得" + rateIncrCouponDefDO.getRate().doubleValue() + "%的加息券<span style=\"color: #8CEA00\"> x 2</span>！";
								}
								rateIncrCouponDefService.send2User(couponId, joinDO.getUserId(), false, "2周年大转盘抽奖赠送加息券");
								joinDO.setRewardResp(rewardResp);
							}
						}
						if ("1".equals(rewardType) || "4".equals(rewardType)) {
							CashCouponDefDO couponDef = cashCouponDefService.get(CashCouponDefDO.class, couponId);
							if (couponDef != null) {
								String rewardResp = "恭喜您，获得" + couponDef.getAmount() + "元的现金券！";
								if (!isUseSendChange) {
									rewardResp = "恭喜您，获得" + couponDef.getAmount() + "元的现金券<span style=\"color: #8CEA00\"> x 2</span>！";
									cashCouponDefService.send2UserWithMessage(couponDef.getId(), joinDO.getUserId(), false,"2周年大转盘抽奖赠送现金券");
								}
								cashCouponDefService.send2UserWithMessage(couponDef.getId(), joinDO.getUserId(), false,"2周年大转盘抽奖赠送现金券");
								joinDO.setRewardResp(rewardResp);
							}
						}
						// 理财金
						if ("2".equals(rewardType) || "7".equals(rewardType)) {
							int expreAmountVal = 0;
							Random rand = new Random();
							if (couponId.equals("act-two-anniversary-celebrate-lottery-experience-1")) {
								expreAmountVal = rand.nextInt(991)+10;
							} else if(couponId.equals("act-two-anniversary-celebrate-lottery-experience-100")) {
								expreAmountVal = rand.nextInt(1201)+100;
							}
							BigDecimal exprBuyAmount = new BigDecimal(expreAmountVal);
							FinancingTargetDO exprTarget = financingTargetService.find(FinancingTargetConstant.TAG_ACT_EXPR, exprBuyAmount);
							if(exprTarget == null) {
								return;
							}
							
							RewardBidService.BuyParam buyParam = new RewardBidService.BuyParam();
							buyParam.setBuyAmount(exprBuyAmount);
							buyParam.setTargetId(exprTarget.getId());
							buyParam.setUserId(joinDO.getUserId());
							
							String rewardResp = "恭喜您，获得" + expreAmountVal + "元的理财金！";
							if (!isUseSendChange) {
								rewardResp = "恭喜您，获得" + expreAmountVal + "元的理财金<span style=\"color: #8CEA00\"> x 2</span>！";
								rewardBidService.doBuy(buyParam);
							}
							joinDO.setRewardResp(rewardResp);
							rewardBidService.doBuy(buyParam);
						}
						// 机会减少
						int days = DateUtil.days(activity.getBeginTime(), activity.getEndTime());
						CacheUtil.setAttribute("act.anniversary.2017lotterydrawchance." + joinDO.getUserId(), String.valueOf(Integer.parseInt(currentLotteryDrawChance)-1), days * 24 * 60 * 60);
						
						if (isUseSendChange) {
							int sencodes = (int) ((activity.getEndTime().getTime()-new Date().getTime()) / 1000);
							CacheUtil.setAttribute("act.anniversary.2017lotterydrawchance.usesendchangeflag." + joinDO.getUserId() + DateUtil.formatDate(new Date()), "1", sencodes);
						}
						
						joinDO.setRewardType(rewardType);
						joinDO.setStatus("success");
					}
				}
			}
			
			AssertUtil.assertTrue(activityJoinService.updateSkipCheckOwner(joinDO), "REWARD_FAIL");
		}
		
	}
	
	// 集结号活动
	private void anniversaryActivityExchangeCoupon(String userId, int currentInviteSoy, int needExchangeSoy, String rateIncrId){		
		for (int i=0; i<needExchangeSoy; i++) {
			CashCouponDefDO couponDef10 = cashCouponDefService.get(CashCouponDefDO.class, "friend-regist");
			if (couponDef10 != null) {
				cashCouponDefService.send2UserWithMessage(couponDef10.getId(), userId, false,"2周年活动集结号兑换10元现金券");
			}
			
			CashCouponDefDO couponDef40 = cashCouponDefService.get(CashCouponDefDO.class, "friend-invest");
			if (couponDef40 != null) {
				cashCouponDefService.send2UserWithMessage(couponDef40.getId(), userId, false,"2周年活动集结号兑换40元现金券");
			}
		}
		
		RateIncrCouponDefDO rateIncrCouponDefDO = rateIncrCouponDefService.get(RateIncrCouponDefDO.class, rateIncrId);
		if (rateIncrCouponDefDO != null) {
			rateIncrCouponDefService.send2User(rateIncrCouponDefDO.getId(), userId, false, "2周年宝箱大探险活动开启宝箱赠送"+ rateIncrCouponDefDO.getRate() +"%加息券");
		}
	}
	// 获得不同兑换类型需要的邀请兑换豆
	private int getNeedExchangeSoy(int exchangeSoyType) {
		int needExchangeSoy = 0;
		
		switch (exchangeSoyType) {
		case 1:
			needExchangeSoy = 1;
			break;
		case 2:
			needExchangeSoy = 2;
			break;
		case 3:
			needExchangeSoy = 4;
			break;
		case 4:
			needExchangeSoy = 8;
			break;
		case 5:
			needExchangeSoy = 10;
			break;
		}
		
		return needExchangeSoy;
	}
	// 获得不同兑换类型赠送的加息券ID
	private String getRateIncrByType(int exchangeSoyType) {
		String rateIncrId = "";
		
		switch (exchangeSoyType) {
		case 1:
			rateIncrId = "act-two-anniversary-celebrate-rate-incr-0.5";
			break;
		case 2:
			rateIncrId = "act-two-anniversary-celebrate-rate-incr-0.7";
			break;
		case 3:
			rateIncrId = "act-two-anniversary-celebrate-rate-incr-1.0";
			break;
		case 4:
			rateIncrId = "act-two-anniversary-celebrate-rate-incr-1.5";
			break;
		case 5:
			rateIncrId = "act-two-anniversary-celebrate-rate-incr-2.0";
			break;
		}
		
		return rateIncrId;
	}
	
	// 获取宝箱的现金券数组
	private String[] getBoxCouponArray(int openBoxType) {
		String[] couponArray = new String[4];
		switch (openBoxType) {
		case 1:
			couponArray[0] = "act-two-anniversary-celebrate-bronze-coupon-0.5";
			couponArray[1] = "act-two-anniversary-celebrate-bronze-coupon-0.1";
			couponArray[2] = "act-two-anniversary-celebrate-bronze-coupon-0.37";
			couponArray[3] = "act-two-anniversary-celebrate-bronze-coupon-0.03";
			break;
		case 2:
			couponArray[0] = "act-two-anniversary-celebrate-gold-coupon-0.47";
			couponArray[1] = "material-jingdong-ecard-50";
			couponArray[2] = "act-two-anniversary-celebrate-gold-coupon-0.1";
			couponArray[3] = "material-jingdong-ecard-100";
			break;
		case 3:
			couponArray[0] = "act-two-anniversary-celebrate-diamond-coupon-0.5";
			couponArray[1] = "material-jingdong-ecard-200";
			couponArray[2] = "act-two-anniversary-celebrate-diamond-coupon-0.1";
			couponArray[3] = "act-two-anniversary-celebrate-diamond-coupon-0.03";
			break;
		case 4:
			couponArray[0] = "act-two-anniversary-celebrate-king-coupon-0.5";
			couponArray[1] = "material-ipadmini";
			couponArray[2] = "material-wurenji";
			couponArray[3] = "material-iphone7";
			break;
		}
		
		return couponArray;
	}
	// 开启宝箱
	private Map<String, String> openBox(int openBoxType, boolean isUseChange, String userId, int integral, String[] couponArray) {
		StringBuffer luckStr = new StringBuffer();
		String luckA = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
		String luckB = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
		String luckC = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
		switch (openBoxType) {
		case 1:
			luckStr.append(luckA).append("AAA")
			.append("BBBBBBBBBB")
			.append(luckC)
			.append("DDD");
			break;
		case 2:
			luckStr.append(luckA)
			.append(luckB).append("BBBBBBBBBB")
			.append("CCCCCCCCCC")
			.append("DDD");
			break;
		case 3:
			luckStr.append(luckA).append("AAA")
			.append(luckB)
			.append("CCCCCCCCCCCCCCCCC")
			.append("DDD");
			break;
		case 4:
			luckStr.append("AAAAAAAAAA")
			.append("BBBBBBB")
			.append("CCC")
			.append("");
			break;
		}
		
		char rewardResp = StringUtil.tryLuck(luckStr.toString());
		if (!isUseChange) {
			vcoinWalletService.subtract(userId, integral, "TWO_ANNIVERSARY_CELEBRATE_ONLINE", "2周年庆开启宝箱活动");
		}
		
		Map<String, String> boxRewardMap = new HashMap<String, String>();
		switch (rewardResp) {
		case 'A':
			boxRewardMap.put("rewardType", "1");
			boxRewardMap.put("rewardCoupon", couponArray[0]);
			break;
		case 'B':
			boxRewardMap.put("rewardType", "2");
			boxRewardMap.put("rewardCoupon", couponArray[1]);
			break;
		case 'C':
			boxRewardMap.put("rewardType", "3");
			boxRewardMap.put("rewardCoupon", couponArray[2]);
			break;
		case 'D':
			boxRewardMap.put("rewardType", "4");
			boxRewardMap.put("rewardCoupon", couponArray[3]);
			break;
		default:
			break;
		}
		
		return boxRewardMap;
	}
	// 获得不同宝箱类型需要的开启积分
	private int getNeedBoxIntegral(int openBoxType) {
		int needBoxIntegral = 0;
		
		switch (openBoxType) {
		case 1:
			needBoxIntegral = 300;
			break;
		case 2:
			needBoxIntegral = 5888;
			break;
		case 3:
			needBoxIntegral = 20000;
			break;
		case 4:
			needBoxIntegral = 180000;
			break;
		}
		
		return needBoxIntegral;
	}
	
	// 大转盘抽奖
	private Map<String, String> lottery() {
		Map<String, String> lotteryMap = new HashMap<String, String>();
		char rewardResp = (char) (new Random().nextInt(7) + 65);
		
		switch (rewardResp) {
		case 'A':
			lotteryMap.put("rewardType", "1");
			lotteryMap.put("rewardCoupon", "act-two-anniversary-celebrate-lottery-cash-10");
			break;
		case 'B':
			lotteryMap.put("rewardType", "2");
			lotteryMap.put("rewardCoupon", "act-two-anniversary-celebrate-lottery-experience-1");
			break;
		case 'C':
			lotteryMap.put("rewardType", "3");
			lotteryMap.put("rewardCoupon", "act-two-anniversary-celebrate-lottery-rate-0.3");
			break;
		case 'D':
			lotteryMap.put("rewardType", "4");
			lotteryMap.put("rewardCoupon", "act-two-anniversary-celebrate-lottery-cash-5");
			break;
		case 'E':
			lotteryMap.put("rewardType", "5");
			lotteryMap.put("rewardCoupon", "act-two-anniversary-celebrate-lottery-rate-1.0");
			break;
		case 'F':
			lotteryMap.put("rewardType", "6");
			lotteryMap.put("rewardCoupon", "act-two-anniversary-celebrate-lottery-rate-0.5");
			break;
		case 'G':
			lotteryMap.put("rewardType", "7");
			lotteryMap.put("rewardCoupon", "act-two-anniversary-celebrate-lottery-experience-100");
			break;
		default:
			break;
		}
		
		return lotteryMap;
	}

}
